<template>
  <div class="u-link-view">
    <slot></slot>
  </div>
</template>
<script>
import {defineComponent, inject, provide} from "vue";
import {LinkContext, ViewContext, VisibleContext} from "@/components/view/Context";
import {
  LinkViewContextKey,
  LinkViewPosition,
  PositionConst,
  ViewContextKey,
  VisibleContextKey
} from "@/utils/ProvideKeys";

export default defineComponent({
    name: "ULinkView",
    props: {
        // 功能名称 比如 用户管理
        name: {type: String, default: ''},
        uid: {type: String, required: true},
        rowKey: {type: String, default: 'id'},
    },
    setup({uid}) {
        let viewContext = inject(ViewContextKey);
        if(viewContext == null) {
          throw new Error(`ULinkView组件必须作为UView的子组件`);
        }

        let parentContext = inject(LinkViewContextKey);
        const linkContext = new LinkContext(uid, viewContext, parentContext || viewContext);

        let visibleContext;
        // 收集所有子LinkView上下文
        let position = inject(LinkViewPosition);
        if(position != PositionConst.Page) {
          visibleContext = inject(VisibleContextKey);
          if(visibleContext instanceof VisibleContext) {
            visibleContext.childLinkContext.push(linkContext);
          }
        }

        provide(LinkViewContextKey, linkContext);
        return {linkContext, viewContext, visibleContext}
    },
    mounted() {
      // LinkView组件不在UDrawer或UModal组件下面
      if(!(this.visibleContext instanceof VisibleContext)) {
        this.linkContext.getQueryFunc().forEach(item => item.trigger());
      }
    },
    methods: {
        /**
         * @return {ViewContext}
         */
        getViewContext() {
            return this.viewContext;
        },

        /**
         * @return {LinkContext}
         */
        getLinkContext() {
            return this.linkContext;
        }
    }
})
</script>